package com.atguigu.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.atguigu.exceptionhandler.GUliException;
import com.atguigu.service.VodService;
import com.atguigu.utils.ConstantVodUtils;
import com.atguigu.utils.R;
import com.atguigu.utils.VodTest;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadVideo(MultipartFile file) {

            String fileName= file.getOriginalFilename();

            String title=fileName.substring(0,fileName.lastIndexOf("."));

            String videoId = null;
            InputStream inputStream=null;
            try {
                inputStream = file.getInputStream();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            if(response.isSuccess()){
                videoId = response.getVideoId();
                return videoId;
            }else{
                //videoId = response.getVideoId();
                throw new GUliException(20001,"上传失败");
            }




    }

    @Override
    public void removeAllVideo(List<String> videoList) {


        try {
            DefaultAcsClient client = VodTest.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            DeleteVideoRequest request = new DeleteVideoRequest();
            String videoIds = StringUtils.join(videoList.toArray(), ",");
            request.setVideoIds(videoIds);
            client.getAcsResponse(request);
        }catch (Exception e){
            e.printStackTrace();
            throw new GUliException(20001,"删除失败");

        }
    }
}
